<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Laracasts\Presenter\PresentableTrait;

class User extends Authenticatable
{
    use Notifiable, HasRoles, PresentableTrait;

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $table = 'biz_users';

    protected $presenter = 'App\Http\Presenters\UserPresenter';

    //protected $guard_name = 'admin';

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $guarded = array();

    public $timestamps = false;
   
    public function branch()
    {
        return $this->belongsTo('App\Models\Mgt\Branch');
    }

    public function school()
    {
        return $this->belongsTo('App\Models\Mgt\School');
    }

    public function summary()
    {
        return $this->hasOne('App\Models\Summary','uid','id');
    }

    public function tracks()
    {
        return $this->hasMany('App\Models\Track','uid','id')->orderBy('date','DESC');
    }

    /**
     * 培训报名记录
     * @return [type] [description]
     */
    public function enrols($pid)
    {
        return \App\Models\Edu\Enrol::where('publish_id', $pid)
            ->where('uid', $this->id)
            ->get();
    }

    /*
    本次培训是否可以报名
     */
    public function canEnrol($pid)
    {
        $publish = \App\Models\Edu\Publish::find($pid);

        if($publish->limit <= 0) return true;

        $enrols = $this->enrols($pid);

        if ( count($enrols) >= $publish->limit ) return false;

        return true;
    }

    /*
    借阅记录
     */
    public function borrows()
    {
      return $this->hasMany('App\Models\Borrow','uid','id')->orderBy('id','DESC');
    }

    /*
    已还书籍
     */
    public function returns()
    {
      return $this->hasMany('App\Models\Borrow','uid','id')->where('status',1)->orderBy('id','DESC');
    }

    /*
    未还书籍
     */
    public function overdue()
    {
        return $this->hasMany('App\Models\Borrow','uid','id')->where('status',0);
    }

    /*
    签到记录
     */
    public function records()
    {
        return $this->hasMany('App\Models\Record','uid','id')->orderBy('date','DESC');
    }

        
    /*
    常规活动是否签到
     */
    public function signed($aid, $type)
    {   
        if( $type == 3 && $this->type == 2) return true;

        $track = \App\Models\Track::where('aid', $aid)
            ->where('uid', $this->id)
            ->where('type', $type)
            ->first();

        if ( $track ) return true;

        return false;
    }


    /*
    报名活动是否报名
     */
    public function applied($aid, $type)
    {
        $track = \App\Models\Track::where('aid', $aid)
            ->where('uid', $this->id)
            ->where('sign', 1)
            ->where('type', $type)
            ->first();

        if ( $track ) return true;

        return false;
    }


    /*
    报名活动是否签到
     */
    public function checked($aid)
    {
        $track = \App\Models\Track::where('aid', $aid)
            ->where('uid', $this->id)
            ->where('check', 1)
            ->first();

        if ( $track ) return true;

        return false;
    }


    

    /**
     * 培训课程是否已经报名
     * @param  [type] $pid [description]
     * @param  [type] $gid [description]
     * @return [type]      [description]
     */
    public function grade($pid, $gid)
    {
        $result = \App\Models\Edu\Enrol::where('publish_id', $pid)
            ->where('grade_id', $gid)
            ->where('uid', $this->id)
            ->first();
            
        if(!!$result) 
            return true;

        return false;
    }


    public function setEnrol($request, $grade)
    {
        //额满限招班一旦报名就确认录取
        $status = 1;
        if( $grade->limited == 1)
            $status = 2;

        $enrol = new \App\Models\Edu\Enrol;

        $enrol->publish_id = $request->publish_id;
        $enrol->plan_id = $request->plan_id;
        $enrol->uid = $this->id;
        $enrol->account = $this->account;
        $enrol->category_id = $request->category_id;
        $enrol->grade_id = $request->grade_id;
        $enrol->status = $status;
        $enrol->source = $request->source;
        //dd($grade->name);
        return $enrol->save();
    }


    public function setTrack($aid, $type = null, $sign = false)
    {
        $track = new \App\Models\Track;

        $track->aid = $aid;
        $track->uid = $this->id;
        $track->account = $this->account;
        $track->type = empty($type)?$this->type:$type;
        $track->sign = $sign?1:0;
        $track->date = time();
        //dd($track);
        return $track->save();
    }


    public function setRecord(\App\Models\User $target, $aid, $amount, $flag, $type = null)
    {
        $balance = $this->summary->points;

        $record = new \App\Models\Record;

        $record->uid = $this->id;
        $record->account = $this->account;
        $record->tid = $target->id;
        $record->aid = $aid;
        $record->flag = $flag;
        $record->type = empty($type)?$this->type:$type;
        $record->amount = $amount;
        $record->balance = ($flag == FLAG_DEBIT) ? $balance+$record->amount : $balance-$record->amount;
        $record->status = 1;
        $record->date = time();
        $record->save();
        return $record->balance;

    }


    public function setSummary($field, $point = null)
    {
        switch ($field)
        {
            case 'signs':
                ++$this->summary->signs;
                $this->summary->points = $point;
                break;
            case 'borrows':
                ++$this->summary->borrows;
                break;
            case 'returns':
                ++$this->summary->returns;
                break;
            case 'points':
                $this->summary->points = $point;
                break;
            default:
                break;
        }
        $this->summary->updated_at = time();
        $this->summary->update();
    }

    /*
    读者
     */
    public function scopeReader($query)
    {       
        return $query->where('type', 1);
    }

    /*
    志愿者
     */
    public function scopeVolunteer($query)
    {       
        return $query->where('type', 2);
    }


    /**
     * [年龄检测]
     * @param  [type]  $birthday [description]
     * @param  integer $valid    [description]
     * @return [type]            [description]
     */
    public static function checkBirthday($birthday, $valid = 80)
    {
        if(strlen($birthday) != 8)
            return false;

        $y = substr($birthday, 0, 4);
        $m = substr($birthday, 4, 2);
        $d = substr($birthday, 6, 2);
        $year = date('Y');

        if ( !checkdate($m,$d,$y) ) {
            return false;
        }
        else{
            if( ($year - $y)<0 )
                return false;
            if( ($year - $y)>$valid )
                return false;
        }

        return true;
    }


    public static function checkMobile($mobile, $type)
    {
        $row = self::where('mobile', $mobile)->where('type', $type)->get();

        if (count( $row ) > 0) return true;

        return false;
    }


    public static function checkIdcard($idcard, $type)
    {
        $row = self::where('idcard', $idcard)->where('type', $type)->get();

        if (count( $row ) > 0) return true;

        return false;
    }
}
